package com.ygxsk.carhome.ui.livefee;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mmkv.MMKV;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.FeeLiveButton;
import com.ygxsk.carhome.enumwrap.FeeLiveOtherType;
import com.ygxsk.carhome.enumwrap.FeePayType;
import com.ygxsk.carhome.enumwrap.FeePaymentWaterOrEleType;
import com.ygxsk.carhome.event.EventFeeWaterMain;
import com.ygxsk.carhome.event.EventPay;
import com.ygxsk.carhome.helper.PushConstants;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.MyFeeLivingWaterAddListener;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.AlipayPayBean;
import com.ygxsk.carhome.response.FeeLivingExpensesWaterBean;
import com.ygxsk.carhome.response.FeePayTypeListBean;
import com.ygxsk.carhome.response.FeeWaterOutSideBean;
import com.ygxsk.carhome.response.PayParameterResult;
import com.ygxsk.carhome.response.WechatPayBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusWithFeePayTypeListBean;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.FeeWaterFragmentAdapter;
import com.ygxsk.carhome.ui.paintbook.PayResult;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.ClearEditTextTouch;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/1/5  9:43
 * @Description:水费界面的activity的页面
 */
public class FeeWaterActivity extends ErrorActivity {

    @BindView(R.id.refreshlayoutfeelivefragmentwat)
    SmartRefreshLayout refreshLayoutFeeLiveFragmentWat;

    @BindView(R.id.recyclerviewinfeelivefragmentwat)
    RecyclerView recyclerViewInFeeLiveFragmentWat;

    //顶部店铺的名字-用在顶部的
    @BindView(R.id.textviewstorenamewater)
    TextView textViewStoreNameWater;

    //顶部 绑定几个电表数量的布局
    @BindView(R.id.textViewStoreCountWater)
    TextView textViewStoreCountWater;

    //底部选中几条数据
    @BindView(R.id.textviewcountnumberwater)
    TextView textViewCountNumberWater;

    //底部计算的总价格数量
    @BindView(R.id.textViewPriceAmountWater)
    TextView textViewPriceAmountWater;

    //底部【去结算】按钮
    @BindView(R.id.roundbuttontopaymentfooterwater)
    RoundTextView roundButtonToPaymentFooterWater;


//    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//    private static final String ARG_PARAM_INDEX = "arg_param_index";
//    private static final String ARG_PARAM_TITLE_NAME = "arg_param_title_name";
//    private String arg_param_index;
//    private String arg_param_title_name;

    private BasePopupView basePopupView_payType;


    //电费列表的适配器
    private FeeWaterFragmentAdapter feeWaterFragmentAdapter;

    //支付方式列表的外侧总列表
    private ArrayList<FeePayTypeListBean> feePayTypeListBeanArrayListDatas = new ArrayList<>();
    //该页面的适配器内容
    private ArrayList<FeeLivingExpensesWaterBean> mDataResources = new ArrayList<>();

    //默认0值，多地方用到
    private BigDecimal bigDecimalZero;
    //footerview的整改总金额；
    private BigDecimal stockSum_upLoad;

    //支付宝的支付标识内容
    private static final int SDK_PAY_FLAG = 1101;
    //微信支付的注册id
    private IWXAPI mWinXinApi;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case SDK_PAY_FLAG: {//支付处理内容。。。

                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, PushConstants.ALIPAY_9000)) {

                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showShort(getResources().getString(R.string.alipay_pay_success));

                        method_handler_success_for_alipayOrweChat();

                    } else {

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort(getResources().getString(R.string.alipay_pay_error));

                    }

                    break;
                }

                default:
                    break;
            }


        }
    };

    /**
     * 支付宝支付业务
     * 2018年11月22日的时候发现新版的支付宝支付 需要添加权限
     */
    private void method_paymentAlipaySDK(final AlipayPayBean _alipayPayBean) {

        try {

            //do
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(FeeWaterActivity.this);

                    //2020-5-25 17:28:30 第二个参数 的意思是：是否展开支付宝调用时候转圈的进度长条，等待弹窗进度条
                    if (_alipayPayBean != null) {

                        Map<String, String> result = alipay.payV2(_alipayPayBean.getPayInfo(), true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;

                        mHandler.sendMessage(msg);

                    } else {
                        ToastUtils.showShort(getResources().getString(R.string.value_alipaypay_isnull));
                    }
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }


    }

    //处理微信支付的逻辑
    private void method_paymentWeChatSDK(final WechatPayBean _wechatPayBean) {

        try {

            //LogUtils.d("itchen-----微信支付内部 method_paymentWeChatSDK ");

            PayReq req = new PayReq();
            //原始代码
            req.appId = _wechatPayBean.getAppid();
            req.partnerId = _wechatPayBean.getPartnerid();//json.getString("partnerid");
            req.prepayId = _wechatPayBean.getPrepayid();//json.getString("prepayid");
            req.nonceStr = _wechatPayBean.getNoncestr();//json.getString("noncestr");
            req.timeStamp = _wechatPayBean.getTimestamp();//json.getString("timestamp");
            req.packageValue = _wechatPayBean.getPkg();//json.getString("package");
            req.sign = _wechatPayBean.getSign();//json.getString("sign");
            //req.extData = "app data"; // optional//额外携带信息暂时不处理

            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            mWinXinApi.sendReq(req);

        } catch (Exception e) {

            //微信本身的异常 仍然停留在该界面，让他勾选其他支付方式。
            if (e != null) {
                ToastUtils.showShort(getResources().getString(R.string.wechat_error) + getResources().getString(R.string.wechat_error_info) + e.getMessage());
            } else {
                ToastUtils.showShort(getResources().getString(R.string.wechat_error));
            }

        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        bigDecimalZero = new BigDecimal(ConstantSign.BIGDECIMAL_ZERO);

//        if (getArguments() != null) {
//            arg_param_index = getArguments().getString(ARG_PARAM_INDEX);
//            arg_param_title_name = getArguments().getString(ARG_PARAM_TITLE_NAME);
//        }

        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusWithFeePayTypeListBean.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusWithFeePayTypeListBean>() {

                    @Override
                    public void accept(RxBusWithFeePayTypeListBean rxBusWithFeePayTypeListBean) throws Throwable {

                        if (rxBusWithFeePayTypeListBean != null) {

                            if (rxBusWithFeePayTypeListBean.getActionFlag() == ExtraValue.MODIFY_EVALUATE_PAYTYPE_SELECT_FEEWATER_FRAGMENT) {//【标志是水费过来的】；

//                           LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--customerId_upLoad-->" + customerId_upLoad);

//                                {
//                                        "image": "http://222.222.17.184:19181/resource/shop/image/pay/0.png",
//                                        "isEnable": 1,
//                                        "isOnline": 1,
//                                        "payName": "支付宝支付",
//                                        "payRate": 0.0060,
//                                        "payTypeCode": "ALIPAY_APP",
//                                        "payTypeId": 1,
//                                        "sortCode": 1
//                                },
//                                {
//                                        "image": "http://222.222.17.184:19181/resource/shop/image/pay/1.png",
//                                        "isEnable": 1,
//                                        "isOnline": 1,
//                                        "payName": "微信支付",
//                                        "payRate": 0.0060,
//                                        "payTypeCode": "WECHAT_APP",
//                                        "payTypeId": 2,
//                                        "sortCode": 2
//                                }

                                if (rxBusWithFeePayTypeListBean.getFeePayTypeListBean() != null) {

//                                    public enum FeePayType {
//                                        TYPE_ALIPAY("1", "ALIPAY_APP"),
//                                        TYPE_WECHAT("2", "WECHAT_APP");

                                    String payTypeCode = rxBusWithFeePayTypeListBean.getFeePayTypeListBean().getPayTypeCode();

                                    //取出勾选数据
                                    ArrayList<FeeLivingExpensesWaterBean> temp = new ArrayList<>();
                                    if (mDataResources != null && !mDataResources.isEmpty()) {
                                        for (FeeLivingExpensesWaterBean item : mDataResources) {
                                            boolean isChecked = item.isChecked();
                                            if (isChecked) {
                                                temp.add(item);
                                            }
                                        }
                                    }

                                    //上传数据
                                    ArrayList<FeeLivingExpensesWaterUpLoad> tempLikeHashMap = new ArrayList<>();

                                    if (temp != null && !temp.isEmpty()) {

                                        for (FeeLivingExpensesWaterBean itemUpLoad : temp) {
                                            //水表号
                                            String gaugeNo = itemUpLoad.getGaugeNo();
                                            //该水表号对应的金额
                                            BigDecimal myGaugeFinalAmount = itemUpLoad.getAmount();

                                            FeeLivingExpensesWaterUpLoad feeLivingExpensesWaterUpLoad = new FeeLivingExpensesWaterUpLoad();
                                            feeLivingExpensesWaterUpLoad.setGaugeNo(gaugeNo);

                                            if (myGaugeFinalAmount != null) {
                                                feeLivingExpensesWaterUpLoad.setFinalAmount(myGaugeFinalAmount.toString());
                                            } else {
                                                feeLivingExpensesWaterUpLoad.setFinalAmount(CommUtils.formatComma2BigDecimal(ConstantSign.BIGDECIMAL_ZERO).toString());
                                            }

                                            tempLikeHashMap.add(feeLivingExpensesWaterUpLoad);

                                        }

                                    }
//                                        String gaugeListUpLoad = JSON.toJSONString(tempLikeHashMap);
//                                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "gaugeListUpLoad-->" + gaugeListUpLoad);
                                    //itchen-->gaugeListUpLoad-->[{"finalAmount":"0.00","gaugeNo":"340119017114"},{"finalAmount":"0.00","gaugeNo":"236910010720"},{"finalAmount":"0.00","gaugeNo":"236910010716"}]
//                                        if (!TextUtils.isEmpty(gaugeListUpLoad)) {
//                                            String removeStr = gaugeListUpLoad.substring(1,gaugeListUpLoad.length()-1);

                                    if (TextUtils.equals(FeePayType.TYPE_ALIPAY.getPayTypeCode(), payTypeCode)) {

                                        //支付宝支付
                                        methd_to_payMent_WeChatSDK_or_AlipaySDK(FeePayType.TYPE_ALIPAY.getPayTypeCode(), tempLikeHashMap);

                                    } else if (TextUtils.equals(FeePayType.TYPE_WECHAT.getPayTypeCode(), payTypeCode)) {

                                        //微信支付
                                        methd_to_payMent_WeChatSDK_or_AlipaySDK(FeePayType.TYPE_WECHAT.getPayTypeCode(), tempLikeHashMap);
                                    }

                                }

                            }
                        }
                    }
                }));

        //----------------------------------------------------------------------


        initloading();

        initViews();

        gainDatas();

        //----------------------------------------------------------------------
        mWinXinApi = WXAPIFactory.createWXAPI(FeeWaterActivity.this, PushConstants.WEIXIN_APPID);//

        if (mWinXinApi != null) {//将该app注册到微信

            mWinXinApi.registerApp(PushConstants.WEIXIN_APPID);

            //建议动态监听微信启动广播进行注册到微信
            FeeWaterActivity.this.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // 将该app注册到微信
                    mWinXinApi.registerApp(PushConstants.WEIXIN_APPID);
                }
            }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
            //----------------------------------------------------------------------

        }

        //微信支付完毕发送消息用到
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //添加适配器之中的监听器
    private MyFeeLivingWaterAddListener myFeeLivingWaterAddListener = new MyFeeLivingWaterAddListener() {
        @Override
        public void inputAmountNumber(String _inputAmountNumber, int indexPosition, FeeLivingExpensesWaterBean _feeLivingExpensesWaterBean) {

            if (feeWaterFragmentAdapter != null) {

                //50元
                RoundTextView textViewAmontFifty = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPosition, R.id.textViewAmontFiftyWat);
                //100元
                RoundTextView textViewAmontOneHundred = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPosition, R.id.textViewAmontOneHundredWat);
                //200元
                RoundTextView textViewAmontTwoHundred = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPosition, R.id.textViewAmontTwoHundredWat);
                //500元
                RoundTextView textViewAmontFiveHundred = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPosition, R.id.textViewAmontFiveHundredWat);
                //输入文本框
//            ClearEditTextTouch editViewInputAmountCustomer = (ClearEditTextTouch) feeElectricFragmentAdapter.getViewByPosition(indexPosition, R.id.editViewInputAmountCustomer);

                if (_feeLivingExpensesWaterBean != null) {

                    if (!TextUtils.isEmpty(_inputAmountNumber)) {
                        BigDecimal bigDecimal = CommUtils.formatComma2BigDecimal(_inputAmountNumber);
                        if (bigDecimal != null) {
                            _feeLivingExpensesWaterBean.setAmount(bigDecimal);
                        } else {
                            _feeLivingExpensesWaterBean.setAmount(bigDecimalZero);
                        }
                    } else {
                        _feeLivingExpensesWaterBean.setAmount(bigDecimalZero);
                    }

                    //如果选中了【按钮价格】如果清空价格文本框，那么就要设置这个，不然不用设置这个
                    //如果是手动输入的价格，那么按钮点击选中的价格都清空
//                    _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_ZERO.getIndex());

                    CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                    CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                    CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                    CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                }

                method_footerView_priceSettlement();

            }

        }

        @Override
        public void chooseAmountButton(int _currentClickPayButton, String _chooseAmountButton, int indexPositionCurrent, FeeLivingExpensesWaterBean _feeLivingExpensesWaterBean) {

            if (feeWaterFragmentAdapter != null) {

// FeeLiveButton
//1：50元
//2: 100元
//3: 200元
//4: 500元
//                    BUTTON_FIFTY(1, "50"),
//                    BUTTON_ONEHUNDRED(2, "100"),
//                    BUTTON_TWOHUNDRED(3, "200"),
//                    BUTTON_FIVEHUNDRED(4, "500");

                //设置价格是0的


                //旧的 点击哪个按钮的记录
                int indexClickOldLastTimeGetPayFeeButton = _feeLivingExpensesWaterBean.getPayFeeButton();
                //当前正在点击的
//              int indexPositionCurrent = feeElectricFragmentAdapter.getItemPosition(_feeLivingExpensesBean);
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "上次选中的--indexClickOldLastTimeGetPayFeeButton-->" + indexClickOldLastTimeGetPayFeeButton);
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "这次点击的--_currentClickPayButton-->" + _currentClickPayButton);

                //找到四个按钮
                //50元
                RoundTextView textViewAmontFifty = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPositionCurrent, R.id.textViewAmontFiftyWat);
                //100元
                RoundTextView textViewAmontOneHundred = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPositionCurrent, R.id.textViewAmontOneHundredWat);
                //200元
                RoundTextView textViewAmontTwoHundred = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPositionCurrent, R.id.textViewAmontTwoHundredWat);
                //500元
                RoundTextView textViewAmontFiveHundred = (RoundTextView) feeWaterFragmentAdapter.getViewByPosition(indexPositionCurrent, R.id.textViewAmontFiveHundredWat);
                //输入文本框
                ClearEditTextTouch editViewInputAmountCustomer = (ClearEditTextTouch) feeWaterFragmentAdapter.getViewByPosition(indexPositionCurrent, R.id.editViewInputAmountCustomerWat);
                //重置为空；
//                editViewInputAmountCustomer.setText("");

                //-------------------------------------------------------------------------------------------------------------------------------------------------------

                if (_currentClickPayButton == FeeLiveButton.BUTTON_FIFTY.getIndex()) {

                    if (indexClickOldLastTimeGetPayFeeButton == FeeLiveButton.BUTTON_FIFTY.getIndex()) {

                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_ZERO.getIndex());
                        //2024-1-25 17:01:05优化：编辑框不充值为空，因为微信支付，是选中之后，金额就填充到编辑框；；
                        editViewInputAmountCustomer.setText("");

                        //是否有欠款，如果有欠款，那么支付金额就是欠款金额。
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.feeLiveBigDecimalCompareToBalance(_feeLivingExpensesWaterBean.getDeviceBalance()));

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    } else {

                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_FIFTY.getIndex());
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_FIFTY.getValue()));
                        editViewInputAmountCustomer.setText(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_FIFTY.getValue()).toString());

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, true);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    }

                } else if (_currentClickPayButton == FeeLiveButton.BUTTON_ONEHUNDRED.getIndex()) {

                    if (indexClickOldLastTimeGetPayFeeButton == FeeLiveButton.BUTTON_ONEHUNDRED.getIndex()) {

                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_ZERO.getIndex());
                        editViewInputAmountCustomer.setText("");

//                        _feeLivingExpensesBean.setAmount(bigDecimalZero);
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.feeLiveBigDecimalCompareToBalance(_feeLivingExpensesWaterBean.getDeviceBalance()));

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    } else {

                        //选中了100元，
                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_ONEHUNDRED.getIndex());
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_ONEHUNDRED.getValue()));
                        editViewInputAmountCustomer.setText(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_ONEHUNDRED.getValue()).toString());

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, true);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    }


                } else if (_currentClickPayButton == FeeLiveButton.BUTTON_TWOHUNDRED.getIndex()) {

                    if (indexClickOldLastTimeGetPayFeeButton == FeeLiveButton.BUTTON_TWOHUNDRED.getIndex()) {

                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_ZERO.getIndex());
                        editViewInputAmountCustomer.setText("");

//                        _feeLivingExpensesBean.setAmount(bigDecimalZero);
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.feeLiveBigDecimalCompareToBalance(_feeLivingExpensesWaterBean.getDeviceBalance()));

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    } else {

                        //选中了200元，
                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_TWOHUNDRED.getIndex());
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_TWOHUNDRED.getValue()));
                        editViewInputAmountCustomer.setText(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_TWOHUNDRED.getValue()).toString());

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, true);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    }


                } else if (_currentClickPayButton == FeeLiveButton.BUTTON_FIVEHUNDRED.getIndex()) {

                    if (indexClickOldLastTimeGetPayFeeButton == FeeLiveButton.BUTTON_FIVEHUNDRED.getIndex()) {

                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_ZERO.getIndex());
                        editViewInputAmountCustomer.setText("");

//                        _feeLivingExpensesBean.setAmount(bigDecimalZero);
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.feeLiveBigDecimalCompareToBalance(_feeLivingExpensesWaterBean.getDeviceBalance()));

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, false);

                    } else {

                        //选中了500元，
                        _feeLivingExpensesWaterBean.setPayFeeButton(FeeLiveButton.BUTTON_FIVEHUNDRED.getIndex());
                        _feeLivingExpensesWaterBean.setAmount(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_FIVEHUNDRED.getValue()));
                        editViewInputAmountCustomer.setText(CommUtils.formatComma2BigDecimal(FeeLiveButton.BUTTON_FIVEHUNDRED.getValue()).toString());

                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFifty, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontOneHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontTwoHundred, false);
                        CommUtils.RoundTextViewButtonModifyFeeLive(textViewAmontFiveHundred, true);
                    }

                }

                method_footerView_priceSettlement();

            }

        }

        @Override
        public void checkBoxButton(boolean itemIsChecked, int indexPositionCurrent, FeeLivingExpensesWaterBean _feeLivingExpensesWaterBean) {

            if (feeWaterFragmentAdapter != null) {

                CheckBox checkBoxInLiveAdapter = (CheckBox) feeWaterFragmentAdapter.getViewByPosition(indexPositionCurrent, R.id.checkBoxInLiveAdapterWat);

                //当前旧的checkbox是否被选中，
                if (itemIsChecked) {
                    //如果旧值是被选中的状态，那么勾灭它，
                    _feeLivingExpensesWaterBean.setChecked(false);
                    checkBoxInLiveAdapter.setChecked(false);
                } else {
                    _feeLivingExpensesWaterBean.setChecked(true);
                    checkBoxInLiveAdapter.setChecked(true);
                }

                //勾中或者勾灭 都是会计算价格的
                method_footerView_priceSettlement();

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "这条列表的数据-真实价格-->" + _feeLivingExpensesWaterBean.getAmount());

            }
        }

    };


    @Override
    protected int getContentViewId() {
        return R.layout.activity_fee_water;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_water_a));

        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //checkEdit();
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

//        toolbarHelper.setLayoutRight(false, 0, "", null);
        toolbarHelper.setLayoutRight(true, 1, getString(R.string.payment_history), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //物业缴费记录-暂时是通用，将来要怎么样？
                Bundle extra_bundle = new Bundle();
                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, FeeLiveOtherType.TYPE_WATER.getIndex());
                ActivityUtils.startActivity(extra_bundle, PaymentNotesActivity.class);
            }
        });


        //右侧是【编辑】
//        toolbarHelper.setLayoutRight(true, 1, getString(R.string.title_cardverifi_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//                //携带是 客户关怀 过去的 到卡券核销列表
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//
//
//                ActivityUtils.startActivity(extra_bundle, CardDistHistoryActivity.class);
//
//            }
//        });


    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {


        //填充假数据的内容
//        FeeLivingExpensesWaterBean feeLivingExpensesWaterBean0 = new FeeLivingExpensesWaterBean();
//        feeLivingExpensesWaterBean0.setNameCode("10215487");
//        BigDecimal bigDecimal0 = new BigDecimal("-0.01");
//        feeLivingExpensesWaterBean0.setBalancePrice(bigDecimal0);
//        feeLivingExpensesWaterBean0.setTypeInfo("中水");
//
//        FeeLivingExpensesWaterBean feeLivingExpensesWaterBean1 = new FeeLivingExpensesWaterBean();
//        feeLivingExpensesWaterBean1.setNameCode("20201452");
//        BigDecimal bigDecimal1 = new BigDecimal("0.02");
//        feeLivingExpensesWaterBean1.setBalancePrice(bigDecimal1);
//        feeLivingExpensesWaterBean1.setTypeInfo("普水");
//
//        FeeLivingExpensesWaterBean feeLivingExpensesWaterBean2 = new FeeLivingExpensesWaterBean();
//        feeLivingExpensesWaterBean2.setNameCode("60012441");
//        BigDecimal bigDecimal2 = new BigDecimal("0.03");
//        feeLivingExpensesWaterBean2.setBalancePrice(bigDecimal2);
//        feeLivingExpensesWaterBean2.setTypeInfo("特水");

        //添加假数据
//        if (mDataResources != null && !mDataResources.isEmpty()) {
//            mDataResources.clear();
//        }

//        mDataResources.add(feeLivingExpensesWaterBean0);
//        mDataResources.add(feeLivingExpensesWaterBean1);
//        mDataResources.add(feeLivingExpensesWaterBean2);

//      LogUtils.d(ConstantSign.LOGCAT_NOMAL + mDataResources.size());

        //顶部店铺名称
        if (textViewStoreNameWater != null) {
            textViewStoreNameWater.setText(mSession.getShopInfoName());
        }

        text_top_bindCount(0);

        //默认底部结算文字
        //共计0个；默认是0个
        if (textViewCountNumberWater != null) {
            textViewCountNumberWater.setText(Parameterkey.INPUT_FIRST_NUMBER_NOT_ZERO);
        }

        //共计0元；默认是0元
        if (textViewPriceAmountWater != null) {
            if (bigDecimalZero != null) {
                textViewPriceAmountWater.setText(MMKV.defaultMMKV().decodeString(ConstantSign.P_CURRENCYSYMBOL, StringUtils.getString(R.string.yangjiaocurrencysymbol)) + bigDecimalZero.toString());
            }
        }

        //去掉动画内容
        if (recyclerViewInFeeLiveFragmentWat != null) {
            RecyclerView.ItemAnimator animator = ((RecyclerView) recyclerViewInFeeLiveFragmentWat).getItemAnimator();
            if (animator != null) {
                ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
            }
        }

        recyclerViewInFeeLiveFragmentWat.setLayoutManager(new MyLinearLayoutManager(this));

        //添加适配器内容
//        feeWaterFragmentAdapter = new FeeWaterFragmentAdapter(R.layout.feeelectricfragmentadapter, mDataResources);
        feeWaterFragmentAdapter = new FeeWaterFragmentAdapter(R.layout.feewaterfragmentadapter, mDataResources);
        //事件监听；
        feeWaterFragmentAdapter.setMyFeeLivingExpensesWaterAddListener(myFeeLivingWaterAddListener);
        recyclerViewInFeeLiveFragmentWat.setAdapter(feeWaterFragmentAdapter);

//        feeElectricFragmentAdapter.removeAllHeaderView();
//        feeElectricFragmentAdapter.removeAllFooterView();
//        feeElectricFragmentAdapter.addHeaderView(getHeaderView(recyclerViewInFeeLiveFragment));
//        feeElectricFragmentAdapter.addFooterView(getFooterView(recyclerViewInFeeLiveFragment));

        feeWaterFragmentAdapter.notifyDataSetChanged();


        feeWaterFragmentAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "setOnItemClickListener-position=>" + position);

                FeeLivingExpensesWaterBean feeLivingExpensesWaterBean = (FeeLivingExpensesWaterBean) adapter.getItem(position);

                if (myFeeLivingWaterAddListener != null) {
                    myFeeLivingWaterAddListener.checkBoxButton(feeLivingExpensesWaterBean.isChecked(), position, feeLivingExpensesWaterBean);
                }

            }
        });

        feeWaterFragmentAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                FeeLivingExpensesWaterBean feeLivingExpensesWaterBean = (FeeLivingExpensesWaterBean) adapter.getItem(position);

                switch (view.getId()) {

                    case R.id.textViewAmontFiftyWat: {//50

                        //回调设置点击的;这里逻辑有一个类似开关，【开启 和 关闭】
                        if (myFeeLivingWaterAddListener != null) {
                            myFeeLivingWaterAddListener.chooseAmountButton(FeeLiveButton.BUTTON_FIFTY.getIndex(), FeeLiveButton.BUTTON_FIFTY.getValue(), position, feeLivingExpensesWaterBean);
                        }

                        break;
                    }

                    case R.id.textViewAmontOneHundredWat: {//100

                        if (myFeeLivingWaterAddListener != null) {
                            myFeeLivingWaterAddListener.chooseAmountButton(FeeLiveButton.BUTTON_ONEHUNDRED.getIndex(), FeeLiveButton.BUTTON_ONEHUNDRED.getValue(), position, feeLivingExpensesWaterBean);
                        }

                        break;
                    }

                    case R.id.textViewAmontTwoHundredWat: {//200

                        if (myFeeLivingWaterAddListener != null) {
                            myFeeLivingWaterAddListener.chooseAmountButton(FeeLiveButton.BUTTON_TWOHUNDRED.getIndex(), FeeLiveButton.BUTTON_TWOHUNDRED.getValue(), position, feeLivingExpensesWaterBean);
                        }

                        break;
                    }

                    case R.id.textViewAmontFiveHundredWat: {//500

                        if (myFeeLivingWaterAddListener != null) {
                            myFeeLivingWaterAddListener.chooseAmountButton(FeeLiveButton.BUTTON_FIVEHUNDRED.getIndex(), FeeLiveButton.BUTTON_FIVEHUNDRED.getValue(), position, feeLivingExpensesWaterBean);
                        }

                        break;
                    }

                    default:
                        break;
                }

            }
        });

        //条目的点击事件？？  不用分页？

        refreshLayoutFeeLiveFragmentWat.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

//                        pagination_upLoad = Parameterkey.pageNum_default_first;
//
                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (feeWaterFragmentAdapter != null) {
                            feeWaterFragmentAdapter.notifyDataSetChanged();
                        }

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });


        roundButtonToPaymentFooterWater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //通知外侧布局刷新支付逻辑
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "结算点击roundButtonToPaymentFooter--roundButtonToPaymentFooter--roundButtonToPaymentFooter");

                //过滤列表值是否有选中的
                ArrayList<FeeLivingExpensesWaterBean> temps = new ArrayList<>();
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    for (FeeLivingExpensesWaterBean item : mDataResources) {
                        boolean isChecked = item.isChecked();
                        if (isChecked) {
                            temps.add(item);
                        }
                    }
                }

                //没有勾选任何费用，那么给用户提示
                //出厂日期也是必填
                if (temps != null && temps.isEmpty()) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.price_select_water), true);
                    mAlertView.show();
                    return;
                }

                //点击结算
                //过滤 是否选中.
                //搜索要弹窗的：客户信息
                basePopupView_payType = new XPopup.Builder(FeeWaterActivity.this)
                        .hasShadowBg(true)
                        //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面;
                        .isViewMode(true)
                        //.autoDismiss(false)
                        //.isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        //.isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                        //.dismissOnTouchOutside(true)
                        //.notDismissWhenTouchInView()
                        .asCustom(new FeePayPopu(FeeWaterActivity.this,//
                                ExtraValue.MODIFY_EVALUATE_PAYTYPE_SELECT_FEEWATER_FRAGMENT,//标志是水费的支付弹窗
                                feePayTypeListBeanArrayListDatas))//
                        .show();


            }
        });


    }

    //顶部的绑定水表的个数
    private void text_top_bindCount(int count) {

        Delivery.getInstance().post(new Runnable() {
            @Override
            public void run() {
                if (textViewStoreCountWater != null) {
                    textViewStoreCountWater.setText(String.valueOf(count));
                }
            }
        });

    }

    @Override
    protected void gainDatas() {

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (feeWaterFragmentAdapter != null) {
            feeWaterFragmentAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            netWorkError();
//            setEnableLoadmore(refreshLayoutInLeadsActivity, false);
        }

        //获取数据之前，都是要清空底部文字的
        method_footerView_priceSettlement();

    }

    private void getServerDatas() {

//        public enum FeePaymentWaterOrEleType {
//            //    1：水表；2：电表
//            FEEPAYTYPE_WATER("1", "水表"),
//            UPDATETYPE_ELE("2", "电表");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
        map.put(Parameterkey.classify, FeePaymentWaterOrEleType.FEEPAYTYPE_WATER.getIndex());

//        map.put(Parameterkey.createsource, createsource_upLoad);//客户来源：0预约试驾；1预约看车；2自然到店；3以旧换新
//        map.put(Parameterkey.status, status_upLoad);////跟进状态：0:待联系;1:已分配;2:有意向;3无意向;4成功;5战败;6取消预约
//        map.put(Parameterkey.keyWord, keyWord_upLoad);//,搜索关键字
//        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.GETFINANCEGAUGEBYHOUSELIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getFinanceGaugeByHouseList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getFinanceGaugeByHouseList(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(FeeWaterFragment.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<FeeWaterOutSideBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        CommUtils.checkMaterialDialog(materialDialog);
                        methodNotSuccessData(what_method, serverCode, serverMessage);

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);

                        loadingGone();

                    }
                }).subscribe(new Consumer<FeeWaterOutSideBean>() {
                    @Override
                    public void accept(FeeWaterOutSideBean feeWaterOutSideBean) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (feeWaterOutSideBean != null) {

                            //----------------------------------------------------------------------------------------------------
                            //2023-12-23 16:53:43 如果不清空，那么
                            if (feePayTypeListBeanArrayListDatas != null) {
                                feePayTypeListBeanArrayListDatas.clear();
                            }

                            //支付方式列表
                            ArrayList<FeePayTypeListBean> feePayTypeListBeanArrayList = feeWaterOutSideBean.getPayTypeList();

                            if (feePayTypeListBeanArrayList != null && !feePayTypeListBeanArrayList.isEmpty()) {

                                if (feePayTypeListBeanArrayListDatas != null) {
                                    feePayTypeListBeanArrayListDatas.addAll(feePayTypeListBeanArrayList);
                                }

                            }

                            //----------------------------------------------------------------------------------------------------
                            //水表待支付列表信息
                            ArrayList<FeeLivingExpensesWaterBean> feeLivingExpensesWaterArrayList = feeWaterOutSideBean.getGaugeList();

                            if (feeLivingExpensesWaterArrayList != null && !feeLivingExpensesWaterArrayList.isEmpty()) {

                                if (mDataResources != null) {

                                    mDataResources.addAll(feeLivingExpensesWaterArrayList);

                                    //绑定多少个水表
                                    text_top_bindCount(mDataResources.size());

                                }
                            }
                            //---------------------------------------------------------------------------------------------------

                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (feeWaterFragmentAdapter != null) {
                            feeWaterFragmentAdapter.notifyDataSetChanged();
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.GETFINANCEGAUGEBYHOUSELIST_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

                    setEnableLoadmore(refreshLayoutFeeLiveFragmentWat, false);

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));

                }

                break;
            }

            default:
                break;
        }
    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void onStop() {
        super.onStop();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + mFragmentInstance.getClass().getSimpleName() + "--onStop");

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadEventFeeWaterMain(EventFeeWaterMain eventFeeWaterMain) {

        if (eventFeeWaterMain != null) {

            if (eventFeeWaterMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_FEE_WATER_MAIN_PAGE) {

//                if (mDataResources!=null&&!mDataResources.isEmpty()){
//                    mDataResources.clear();
//                }
//
//                if (feeWaterFragmentAdapter!=null){
//                    feeWaterFragmentAdapter.notifyDataSetChanged();
//                }

                gainDatas();

            }

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadEventPayWater(EventPay eventPay) {

        if (eventPay != null) {

            int errorCode = eventPay.getMessage();
            //isOpenWechart = false;//itchen retain先这样，等调试接口再处理

            if (errorCode == BaseResp.ErrCode.ERR_OK) {

                //获取服务器端告知支付成功的接口,然后跳转到结算结果页。
//                gainOrderState(payTokenForPay, 1);
                method_handler_success_for_alipayOrweChat();

            } else if (errorCode == BaseResp.ErrCode.ERR_USER_CANCEL) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付取消");
//                ToastUtils.showShort("支付取消");
                //2018年03月20日逻辑，微信支付失败仍然停留在此界面。
                //gainOrderStateFail(payTokenForPay,0);
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.pop_pay_cancel));

            } else if (errorCode == BaseResp.ErrCode.ERR_AUTH_DENIED) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付失败");
//                ToastUtils.showShort("支付失败");

                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_failed));


            } else if (errorCode == BaseResp.ErrCode.ERR_COMM) {

                //LogUtils.d("itchen-----执行微信支付错误逻辑");
//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付错误");
//                ToastUtils.showShort("支付错误");

                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_wrong));

                //gainOrderStateFail(payTokenForPay,0);
            } else if (errorCode == BaseResp.ErrCode.ERR_SENT_FAILED) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付发送失败");
//                ToastUtils.showShort("支付发送失败");

                //gainOrderStateFail(payTokenForPay,0);
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_send_message_fail));

            } else if (errorCode == BaseResp.ErrCode.ERR_UNSUPPORT) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "不支持错误");
//                ToastUtils.showShort("不支持错误");
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_not_supported_wrong));

                //gainOrderStateFail(payTokenForPay,0);
            } else {
                //retain
//                ToastUtils.showShort("未知错误");
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_unkown_wrong));
            }


        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + mFragmentInstance.getClass().getSimpleName() + "--onDestroy");


        CommUtils.checkBasePopupView(basePopupView_payType);

        if (basePopupView_payType != null) {
            basePopupView_payType.onDestroy();
            basePopupView_payType = null;
        }

        if (mDataResources != null) {
            mDataResources.clear();
//            mDataResources=null;
        }

        if (feePayTypeListBeanArrayListDatas != null) {
            feePayTypeListBeanArrayListDatas.clear();
            feePayTypeListBeanArrayListDatas = null;
        }

        if (feeWaterFragmentAdapter != null) {
            feeWaterFragmentAdapter.notifyDataSetChanged();
            feeWaterFragmentAdapter = null;
        }

        if (mDataResources != null) {
//            mDataResources.clear();
            mDataResources = null;
        }

        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }

        EventBus.getDefault().unregister(this);

    }

    //支付完毕处理 微信支付成功信息
    private void method_handler_success_for_alipayOrweChat() {

        //通知该页面刷新
        EventFeeWaterMain eventFeeWaterMain = new EventFeeWaterMain();
        eventFeeWaterMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_FEE_WATER_MAIN_PAGE);
        EventBus.getDefault().post(eventFeeWaterMain);

        methodSingleSubmitSuccessCustomTitle(FeeWaterActivity.this, getString(R.string.alipay_pay_success), new DoSomeThingListener() {

            @Override
            public void doSomeThing() {

            }
        });


    }

    //价格结算
    private void method_footerView_priceSettlement() {

        //过滤几个被勾中
        if (mDataResources != null && !mDataResources.isEmpty()) {

            //默认是零元。
            stockSum_upLoad = bigDecimalZero;
            //当前的总共多少个
            int countToal = 0;
            //当前的价格
            BigDecimal modifyPrice = new BigDecimal(ConstantSign.BIGDECIMAL_ZERO);

            //默认底部结算文字
            Iterator<FeeLivingExpensesWaterBean> iterator = mDataResources.iterator();

            if (iterator != null) {

                while (iterator.hasNext()) {

                    FeeLivingExpensesWaterBean feeLivingExpensesWaterBean = iterator.next();

                    if (feeLivingExpensesWaterBean != null) {
                        //------------------------------------------------------------------------
                        boolean isChecked = feeLivingExpensesWaterBean.isChecked();

                        //只有选中的才计算，没有选中的不参与计算。
                        if (isChecked) {

                            countToal = countToal + 1;

                            //------------------------------------------------------------------------
                            BigDecimal modifyAmountBigDecimal = feeLivingExpensesWaterBean.getAmount();
                            if (modifyAmountBigDecimal != null) {
                                modifyPrice = modifyPrice.add(modifyAmountBigDecimal);
                                stockSum_upLoad = modifyPrice;
                            }
                            //------------------------------------------------------------------------

                        }

                    }
                }

            }

            //共计0个；默认是0个
            if (textViewCountNumberWater != null) {
                textViewCountNumberWater.setText(String.valueOf(countToal));
            }

            //循环单条做价格计算
//            Iterator<ModifyMiddleTallAddSubmit> iterator = mDataResources.iterator();
//            if (iterator != null) {
//                while (iterator.hasNext()) {
//                    ModifyMiddleTallAddSubmit modifyMiddleTallAddSubmit = iterator.next();
//                    if (modifyMiddleTallAddSubmit != null) {
//                        BigDecimal modifyMustMoneyAmountBigDecimal = modifyMiddleTallAddSubmit.getModifyMustMoneyAmountBigDecimal();
//                        if (modifyMustMoneyAmountBigDecimal != null) {
//                            count = count.add(modifyMustMoneyAmountBigDecimal);
//                            stockSum_upLoad = count;
//                        }
//                    }
//                }
//            }

            //共计0元；默认是0元
            if (textViewPriceAmountWater != null) {
                if (bigDecimalZero != null) {
                    textViewPriceAmountWater.setText(MMKV.defaultMMKV().decodeString(ConstantSign.P_CURRENCYSYMBOL, StringUtils.getString(R.string.yangjiaocurrencysymbol)) + stockSum_upLoad.toString());
                }
            }

        } else {

            //共计0个；默认是0个
            if (textViewCountNumberWater != null) {
                textViewCountNumberWater.setText(Parameterkey.INPUT_FIRST_NUMBER_NOT_ZERO);
            }

            //共计0元；默认是0元
            if (textViewPriceAmountWater != null) {
                if (bigDecimalZero != null) {
                    textViewPriceAmountWater.setText(MMKV.defaultMMKV().decodeString(ConstantSign.P_CURRENCYSYMBOL, StringUtils.getString(R.string.yangjiaocurrencysymbol)) + bigDecimalZero.toString());
                }
            }

        }

    }

    //调用支付方式获取微信支付或者支付宝支付启动数据
    private void methd_to_payMent_WeChatSDK_or_AlipaySDK(String _payType, ArrayList<FeeLivingExpensesWaterUpLoad> _gaugeList) {

//        public enum FeePaymentWaterOrEleType {
//            //    1：水表；2：电表
//            FEEPAYTYPE_WATER("1", "水表"),
//            UPDATETYPE_ELE("2", "电表");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
        map.put(Parameterkey.payType, _payType);//支付方式
        map.put(Parameterkey.gaugeList, _gaugeList);//水表的数组，是一个水表对应一个金额
        map.put(Parameterkey.classify, FeePaymentWaterOrEleType.FEEPAYTYPE_WATER.getIndex());//区分是水表的支付还是电表的支付

//        map.put(Parameterkey.createsource, createsource_upLoad);//客户来源：0预约试驾；1预约看车；2自然到店；3以旧换新
//        map.put(Parameterkey.status, status_upLoad);////跟进状态：0:待联系;1:已分配;2:有意向;3无意向;4成功;5战败;6取消预约
//        map.put(Parameterkey.keyWord, keyWord_upLoad);//,搜索关键字
//        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETGAUGEPAYINFO_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getGaugePayInfo_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getGaugePayInfo(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(FeeWaterFragment.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PayParameterResult>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

//                        CommUtils.checkMaterialDialog(materialDialog);
//                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

//                        CommUtils.checkMaterialDialog(materialDialog);
//                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);

                    }
                }).subscribe(new Consumer<PayParameterResult>() {
                    @Override
                    public void accept(PayParameterResult payParameterResultValue) throws Throwable {

//                        CommUtils.checkMaterialDialog(materialDialog);

                        // TODO: 2023-12-21 15:32 调用支付宝支付的接口
                        if (TextUtils.equals(_payType, FeePayType.TYPE_ALIPAY.getPayTypeCode())) {

                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                //有权限设置
                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_PHONE_STATE)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //2018年11月22日发现支付宝需要添加权限
                                            AndPermission.with(FeeWaterActivity.this)
                                                    .runtime()
                                                    .permission(Permission.READ_PHONE_STATE,//
                                                            Permission.WRITE_EXTERNAL_STORAGE,//
                                                            Permission.READ_EXTERNAL_STORAGE)
                                                    .rationale(new RuntimeRationale())
                                                    .onGranted(new Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> data) {

                                                            LogUtils.d("itchen---->执行调用 method_paymentAlipaySDK---支付宝支付");

                                                            //支付宝SDK调起
                                                            method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());

                                                        }
                                                    }).onDenied(new Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {
                                                            if (AndPermission.hasAlwaysDeniedPermission(FeeWaterActivity.this, permissions)) {
                                                                (new PermissionSetting(FeeWaterActivity.this)).showSetting(ConstantApi.PERMISSION_NORMAL, FeeWaterActivity.this, permissions);
                                                            }
                                                        }
                                                    }).start();
                                        }
                                    });

                                } else {
                                    //支付宝SDK调起
                                    method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());
                                }


                            } else {

                                //高于android13的版本。
                                //有权限设置
                                if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_PHONE_STATE)) {//


                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                                        @SuppressLint("CheckResult")
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //2018年11月22日发现支付宝需要添加权限
                                            XXPermissions.with(FeeWaterActivity.this)
                                                    // 适配分区存储应该这样写
                                                    //.permission(Permission.Group.STORAGE)
                                                    // 不适配分区存储应该这样写
//                                                        .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                                                    .permission(com.hjq.permissions.Permission.READ_PHONE_STATE)//
                                                    .interceptor(new PermissionInterceptor())
                                                    .request(new OnPermissionCallback() {

                                                        @Override
                                                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                            if (!allGranted) {
                                                                return;
                                                            }

                                                            Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                    PermissionNameConvert.getPermissionString(FeeWaterActivity.this, permissions)));

                                                            //微信支付调起
                                                            method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());

                                                        }
                                                    });
                                        }
                                    });

                                } else {
                                    //支付宝SDK调起
                                    method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());
                                }

                            }


                        } else if (TextUtils.equals(_payType, FeePayType.TYPE_WECHAT.getPayTypeCode())) {


                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                //有权限设置
                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_PHONE_STATE)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //2018年11月22日发现支付宝需要添加权限
                                            AndPermission.with(FeeWaterActivity.this)
                                                    .runtime()
                                                    .permission(Permission.READ_PHONE_STATE,//
                                                            Permission.WRITE_EXTERNAL_STORAGE,//
                                                            Permission.READ_EXTERNAL_STORAGE)
                                                    .rationale(new RuntimeRationale())
                                                    .onGranted(new Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> data) {

                                                            LogUtils.d("itchen---->执行调用 method_paymentWeChatSDK---微信支付");

                                                            //支付宝SDK调起
                                                            method_paymentWeChatSDK(payParameterResultValue.getWechatPay());

                                                        }
                                                    }).onDenied(new Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {
                                                            if (AndPermission.hasAlwaysDeniedPermission(FeeWaterActivity.this, permissions)) {
                                                                (new PermissionSetting(FeeWaterActivity.this)).showSetting(ConstantApi.PERMISSION_NORMAL, FeeWaterActivity.this, permissions);
                                                            }
                                                        }
                                                    }).start();
                                        }
                                    });

                                } else {
                                    //微信SDK调起
                                    method_paymentWeChatSDK(payParameterResultValue.getWechatPay());
                                }


                            } else {

                                if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_PHONE_STATE)) {//

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            XXPermissions.with(FeeWaterActivity.this)
                                                    // 适配分区存储应该这样写
                                                    //.permission(Permission.Group.STORAGE)
                                                    // 不适配分区存储应该这样写
//                                                        .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                                                    .permission(com.hjq.permissions.Permission.READ_PHONE_STATE)//
                                                    .interceptor(new PermissionInterceptor())
                                                    .request(new OnPermissionCallback() {

                                                        @Override
                                                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                            if (!allGranted) {
                                                                return;
                                                            }

                                                            Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                    PermissionNameConvert.getPermissionString(FeeWaterActivity.this, permissions)));

                                                            //微信支付调起
                                                            method_paymentWeChatSDK(payParameterResultValue.getWechatPay());

                                                        }
                                                    });

                                        }
                                    });

                                } else {

                                    //微信支付调起
                                    method_paymentWeChatSDK(payParameterResultValue.getWechatPay());

                                }

                            }
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

//                        CommUtils.checkMaterialDialog(materialDialog);

                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });

    }

}